'use client'

import { useState } from 'react'
import { Button, Input, Select, Form, FormField, FormItem, FormLabel } from '@/components/ui/form'
import React from 'react'
import { createClient } from '@/lib/supabase/client'
import { useToast } from '@/components/ui/use-toast'

type GoalFormProps = {
  initialData?: {
    id?: number
    title?: string
    target?: number
    current?: number
    status?: 'in_progress' | 'completed'
  }
  onClose: () => void
  onSubmit: () => void
}

export default function GoalForm({ initialData, onClose, onSubmit }: GoalFormProps) {
  const toast = useToast()
  const [formData, setFormData] = useState({
    title: initialData?.title || '',
    target: initialData?.target || 100,
    current: initialData?.current || 0,
    status: initialData?.status || 'in_progress'
  })
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    // 根据输入类型转换值
    setFormData(prev => ({
      ...prev,
      [name]: name === 'target' || name === 'current' ? Number(value) : value
    }))
  }

  const handleSubmit = async (e: any) => {
    e.preventDefault()
    setLoading(true)
    setError('')

    try {
      const supabase = createClient()
      const { data: { user } } = await supabase.auth.getUser()

      if (!user) {
        throw new Error('User not authenticated')
      }

      if (initialData?.id) {
        // Update existing goal
        const { error } = await supabase
          .from('goals')
          .update({
            title: formData.title,
            target: formData.target,
            current: formData.current,
            status: formData.status,
            updated_at: new Date().toISOString()
          })
          .eq('id', initialData.id)
          .eq('user_id', user.id)

        if (error) throw error
        toast({ title: 'Goal updated successfully' })
      } else {
        // Create new goal
        const { error } = await supabase
          .from('goals')
          .insert({
            user_id: user.id,
            title: formData.title,
            target: formData.target,
            current: formData.current,
            status: formData.status,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString()
          })

        if (error) throw error
        toast({ title: 'New goal created successfully' })
      }

      onSubmit()
      onClose()
    } catch (err: any) {
      setError(err.message || 'Failed to save goal')
      console.error('Error saving goal:', err)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="p-6 bg-white rounded-lg shadow-lg max-w-md mx-auto">
      <h2 className="text-2xl font-bold mb-4">{initialData?.id ? 'Edit Goal' : 'Create New Goal'}</h2>
      {error && <div className="text-red-500 mb-4">{error}</div>}
      <Form onSubmit={handleSubmit}>
        <FormField
          name="title"
          render={({ field }: { field: { name: string; value: string; onChange: (value: string) => void } }) => (
            <FormItem>
              <FormLabel>Goal Title</FormLabel>
              <Input
                name="title"
                value={formData.title}
                onChange={handleChange}
                placeholder="e.g., Reduce anxiety levels"
                required
              />
            </FormItem>
          )}
        />
        
        <div className="grid grid-cols-2 gap-4 mt-4">
          <FormField
            name="target"
            render={({ field }: { field: { name: string; value: number; onChange: (value: number) => void } }) => (
              <FormItem>
                <FormLabel>Target (%)</FormLabel>
                <Input
                  name="target"
                  type="number"
                  min="1"
                  max="100"
                  value={formData.target}
                  onChange={handleChange}
                  required
                />
              </FormItem>
            )}
          />

          <FormField
            name="current"
            render={({ field }: { field: { name: string; value: number; onChange: (value: number) => void } }) => (
              <FormItem>
                <FormLabel>Current (%)</FormLabel>
                <Input
                  name="current"
                  type="number"
                  min="0"
                  max={formData.target}
                  value={formData.current}
                  onChange={handleChange}
                  required
                />
              </FormItem>
            )}
          />
        </div>

        <FormField
          name="status"
          render={({ field }: { field: { name: string; value: string; onChange: (value: string) => void } }) => (
            <FormItem className="mt-4">
              <FormLabel>Status</FormLabel>
              <Select
                name="status"
                value={formData.status}
                onChange={handleChange}
                options={[
                  { value: 'in_progress', label: 'In Progress' },
                  { value: 'completed', label: 'Completed' }
                ]}
              >
              </Select>
            </FormItem>
          )}
        />

        <div className="flex justify-end space-x-4 mt-6">
          <Button type="button" onClick={onClose} variant="outline">
            Cancel
          </Button>
          <Button type="submit" loading={loading}>
            {initialData?.id ? 'Update' : 'Create'}
          </Button>
        </div>
      </Form>
    </div>
  )
}